package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.MaxTextLengthFilter;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.bean.MsgInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.PostInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.StudentBirthdayInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 发送生日祝福
 * Created by Administrator on 2018/7/5 0005.
 */

public class TeacherSendBirthdayWishActivity extends BaseActivity implements View.OnClickListener {
    private ImageView ivBack;
    private TextView tvTtitle;
    private EditText etMsg;
    private TextView tvNum;
    private Button btChooseMsg;
    private Button btSend;
    private LinearLayout llContent;
    private RelativeLayout rlLoading;
    private String passJson;
    private List<String> allMsg;
    //需要发送的祝福语
    private String sendMsg;


    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_send_birthday;
    }

    @Override
    protected void init() {

        initStateBar();

        //初始化视图
        initView();

        //设置输入框的监听
        initListener();

        //获取所有过生日学生的数据集合
        initIntent();

        //请求服务器获取祝福语言
        http();
    }

    /**
     * 输入框的监听
     */
    private void initListener() {
        etMsg.setFilters(new InputFilter[]{new MaxTextLengthFilter(51)});
        etMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String inputText = etMsg.getText().toString().trim();
                if (TextUtils.isEmpty(inputText)) {
                    tvNum.setText("0/50");
                } else {
                    if (inputText.length() > 51) {
                        tvNum.setText("50/50");
                    } else {
                        tvNum.setText(inputText.length() + "/50");
                    }
                }
            }
        });
    }


    /**
     * 初始化视图
     */

    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        etMsg = findViewById(R.id.tv_msg);
        tvNum = findViewById(R.id.tv_num);
        tvTtitle = findViewById(R.id.tv_title);
        tvTtitle.setText("生日祝福");
        btChooseMsg = findViewById(R.id.bt_choose_msg);
        btChooseMsg.setOnClickListener(this);
        btSend = findViewById(R.id.bt_send);
        btSend.setOnClickListener(this);
        llContent = findViewById(R.id.rl_content);
        rlLoading = findViewById(R.id.rl_loading);
    }

    /**
     * 获取所有过生日的学生集合数据
     */
    private void initIntent() {
        passJson = getIntent().getStringExtra("data");
    }


    /**
     * 请求服务器获取祝福语
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "14");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");
        HttpUtils.post(HttpAddress.GETMSG, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }
                if (llContent != null && llContent.getVisibility() != View.VISIBLE) {
                    llContent.setVisibility(View.VISIBLE);
                }
                if (!TextUtils.isEmpty(response)) {
                    MsgInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, MsgInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }


                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            //获取所有的Msg
                            allMsg = info.getData();

                            //显示一条Msg信息
                            showMsg(0);

                        } else {
                            ToastUtils.showShort(Constants.ERRORSTATE + info.getState());
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }

                    } else {
                        Log.i("test", Constants.EMPTY);
                    }

                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 随机选取一条祝福语
     */
    private void showMsg(int type) {
        if (allMsg != null && allMsg.size() != 0) {
            if (type == 0) {
                sendMsg = allMsg.get(0);
            } else {
                int index = (int) (Math.random() * allMsg.size());
                sendMsg = allMsg.get(index);
            }
            etMsg.setText(sendMsg);
            tvNum.setText(sendMsg.length() + "/50");
        }
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.bt_choose_msg) {
            //换一句祝福语
            if (allMsg == null || allMsg.size() == 0) {
                ToastUtils.showShort("服务器没有返回祝福语");
                return;
            } else {
                showMsg(1);
            }
        } else if (id == R.id.bt_send) {
            //发送祝福
            if (allMsg == null || allMsg.size() == 0) {
                ToastUtils.showShort("服务器没有返回祝福语");
                return;
            }

            if (TextUtils.isEmpty(passJson)) {
                ToastUtils.showShort("还未没有选择送祝福的学生");
                return;
            }

            doSendMsgAction();
        }
    }

    /**
     * 发送祝福语的操作
     */
    private void doSendMsgAction() {
        CustomDialogManager.show(this, "发送中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "15");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("platform", "2");
        PostInfo postInfo = new PostInfo();
        postInfo.content = sendMsg;
        postInfo.list = GsonUtil.jsonToList(passJson, StudentBirthdayInfo[].class);
        map.put("students", GsonUtil.objectToJson(postInfo));

        HttpUtils.post(HttpAddress.SENDMSG, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast("发送失败," + BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();

                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("发送成功", false);
                            //通知上个界面也进行页面关闭
                            BusInfo busInfo = new BusInfo();
                            busInfo.type = TeacherBirthdayActivity.CLOSETYPE;
                            EventBus.getDefault().post(busInfo);
                            finish();
                        } else if ("101".equals(info.getState())) {
                            ToastUtils.showShort("参数错误");
                        } else if ("103".equals(info.getState())) {
                            ToastUtils.showShort("服务器间异常");
                        } else {
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }

                    } else {
                        Log.i("test", Constants.EMPTY);
                    }

                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }
}
